<template>
    <div class="container">
      <!-- <canvas id="tutorial" width="1000" height="1000"></canvas> -->
      <a-row class="overlay">
        <a-col :sm="24" >
          <a-empty v-if="queryParamsModel.length === 0" style="margin-bottom: 12px;">
            <div slot="description">
              <span>没有任何查询条件</span>
              <a-divider type="vertical"/>
              <a @click="handleAdd">点击新增</a>
            </div>
          </a-empty>
          <a-form v-else layout="inline">
            <a-row style="margin-bottom: 12px;">
              <a-col :md="12" :xs="24">
                <a-form-item label="过滤条件匹配" :labelCol="{md: 6,xs:24}" :wrapperCol="{md: 18,xs:24}" class="!w-full">
                  <a-select v-model="matchType" :disabled="disabled" class="!w-full">
                    <a-select-option value="AND">AND（所有条件都要求匹配）</a-select-option>
                    <a-select-option value="OR">OR（条件中的任意一个匹配）</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row type="flex" style="margin-bottom:10px" :gutter="16" v-for="(item, index) in queryParamsModel" :key="index">
              <a-col :md="8" :xs="24" style="margin-bottom: 12px;">
                <a-select
                  showSearch
                  v-model="item.fieldName"
                  :options="fieldTreeData"
                  option-filter-prop="children"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="选择查询字段"
                  allowClear
                  :disabled="disabled"
                  class="!w-full"
                  :filterOption="filterOption"
                  @select="(val,option)=>handleSelected(option,item)"
                >
                </a-select>
              </a-col>
              <a-col :md="4" :xs="24" style="margin-bottom: 12px;">
                <a-select :disabled="disabled" placeholder="匹配规则" :value="item.operator" @change="handleRuleChange(item,$event)">
                  <a-select-option value="EQ">等于</a-select-option>
                  <a-select-option value="LIKE">包含</a-select-option>
                  <a-select-option value="NOT_LIKE">不包含</a-select-option>
                  <a-select-option value="LIKE_START">开始是</a-select-option>
                  <a-select-option value="LIKE_END">结尾是</a-select-option>
                  <a-select-option value="IN">在...中</a-select-option>
                  <a-select-option value="NE">不等于</a-select-option>
                  <a-select-option value="GT">大于</a-select-option>
                  <a-select-option value="GE">大于等于</a-select-option>
                  <a-select-option value="LT">小于</a-select-option>
                  <a-select-option value="LE">小于等于</a-select-option>
                </a-select>
              </a-col>
              <a-col :md="8" :xs="24" style="margin-bottom: 12px;">
                <template v-if="item.dictCode">
                  <!-- <template v-if="item.type === 'table-dict'">
                    <z-popup
                      v-model="item.val"
                      :code="item.dictTable"
                      :field="item.dictCode"
                      :orgFields="item.dictCode"
                      :destFields="item.dictCode"
                    ></z-popup>
                  </template>
                  <template v-else> -->
                  <z-multi-select-tag :disabled="disabled" v-bind="getProps(item.fieldName)" v-show="allowMultiple(item)" v-model="item.value" :dictCode="getDictCode(item)" placeholder="请选择"/>
                  <!-- 下拉选择改为下拉搜索 -->
                  <z-search-select-tag :disabled="disabled" v-bind="getProps(item.fieldName)" v-show="!allowMultiple(item)" v-model="item.value" :dict="getDictCode(item)" :trigger-change="true" placeholder="请选择"/>
                </template>
                <!-- <z-popup v-else-if="item.type === 'popup'" :value="item.val" v-bind="item.popup" group-id="superQuery" @input="(e,v)=>handleChangeJPopup(item,e,v)"/> -->
                <z-select-multi-user
                  :disabled="disabled"
                  v-else-if="item.type === 'user' || item.type === 'sel_user'"
                  v-model="item.value"
                  :buttons="false"
                  :multiple="false"
                  placeholder="请选择用户"
                  v-bind="getProps(item.fieldName)"
                  :returnKeys="['id', item.customReturnField || 'username']"
                />
                <z-select-dept
                  :disabled="disabled"
                  v-else-if="item.type === 'dept' || item.type === 'sel_dept'"
                  v-model="item.value"
                  :multi="false"
                  placeholder="请选择部门"
                  v-bind="getProps(item.fieldName)"
                  :customReturnField="item.customReturnField || 'id'"
                />
                <a-select
                  :disabled="disabled"
                  v-else-if="item.options instanceof Array"
                  v-model="item.value"
                  :options="item.options"
                  allowClear
                  placeholder="请选择"
                  v-bind="getProps(item.fieldName)"
                  :mode="allowMultiple(item)?'multiple':''"
                />
                <a-date-picker v-else-if=" item.type=='date' " :disabled="disabled" v-bind="getProps(item.fieldName)" v-model="item.value" placeholder="请选择日期" class="!w-full"></a-date-picker>
                <a-date-picker v-else-if=" item.type=='datetime' " :disabled="disabled" v-bind="getProps(item.fieldName)" v-model="item.value" placeholder="请选择时间" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" class="!w-full"></a-date-picker>
                <a-time-picker v-else-if="item.type==='time'" :disabled="disabled" v-bind="getProps(item.fieldName)" :value="item.value ? moment(item.value,'HH:mm:ss') : null" format="HH:mm:ss" class="!w-full" @change="(time,value)=>item.val=value"/>
                <a-input-number v-else-if=" item.type=='int'||item.type=='number' " v-bind="getProps(item.fieldName)" :disabled="disabled" class="!w-full" placeholder="请输入数值" v-model="item.value"/>
                <a-select v-else-if="item.type=='switch'" :disabled="disabled" v-bind="getProps(item.fieldName)" placeholder="请选择" v-model="item.value">
                  <a-select-option value="Y">是</a-select-option>
                  <a-select-option value="N">否</a-select-option>
                </a-select>
                <a-input v-else :disabled="disabled" v-bind="getProps(item.fieldName)" v-model="item.value" placeholder="请输入值"/>
              </a-col>
              <a-col :md="4" :xs="0" style="margin-bottom: 12px;">
                <a-button @click="handleAdd" :disabled="disabled" icon="plus"></a-button>&nbsp;
                <a-button @click="handleDel( index )" :disabled="disabled" icon="minus"></a-button>
              </a-col>
              <a-col :md="0" :xs="24" style="margin-bottom: 12px;text-align: right;">
                <a-button @click="handleAdd" icon="plus"></a-button>&nbsp;
                <a-button @click="handleDel( index )" icon="minus"></a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </div>
</template>

<script>
import moment from 'moment'
import ZSelectDept from '@/components/zzbiz/ZSelectDept'
import ZSelectMultiUser from '@/components/zzbiz/ZSelectMultiUser'
import ZMultiSelectTag from '@/components/dict/ZMultiSelectTag'
import ZSearchSelectTag from '@/components/dict/ZSearchSelectTag'
import { Empty as AEmpty } from 'ant-design-vue'
export default {
  name: 'SuperQuery',
  mixins: [],
  components: { ZSearchSelectTag, ZSelectDept, ZSelectMultiUser, ZMultiSelectTag, AEmpty },
  props: {
    /*
       fieldList: [{
          value:'',
          text:'',
          type:'',
          dictCode:'' // 只要 dictCode 有值，无论 type 是什么，都显示为字典下拉框
       }]
       type:date datetime int number string
      * */
    fieldList: {
      type: Array,
      required: true
    },
    queryParam: {
      type: Object,
      default: () => {}
    },
    disabled: Boolean,
    isNewLine: { // 控制是否需要初始化插入
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      moment,
      fieldTreeData: [],
      queryParamsModel: [],
      matchType: 'AND',
      fieldObj: {}
    }
  },
  watch: {
    fieldList: {
      deep: true,
      immediate: true,
      handler(val) {
        const mainData = []
        val.forEach(item => {
          this.fieldObj[item.value] = item
          const data = { ...item }
          data.label = data.label || data.text
          mainData.push(data)
        })
        console.log(this.fieldObj)
        this.fieldTreeData = mainData
      }
    },
    queryParam: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.matchType = val.type || 'AND'
          this.queryParamsModel = val.criterions || []
        }
      }
    }
  },
  methods: {
    handleAdd() {
      this.addNewLine()
    },
    addNewLine() {
      this.queryParamsModel.push({ operator: 'EQ' })
    },
    handleDel(index) {
      this.queryParamsModel.splice(index, 1)
    },
    handleSelected(node, item) {
      const { type, options, dictCode, dictTable, customReturnField, popup } = node.data.props
      item['type'] = type
      item['options'] = options
      item['dictCode'] = dictCode
      item['dictTable'] = dictTable
      item['customReturnField'] = customReturnField
      if (popup) {
        item['popup'] = popup
      }
      this.$set(item, 'value', undefined)
    },
    getQueryParams() {
      if (!this.isNullArray(this.queryParamsModel)) {
        const event = {
          type: this.matchType,
          criterions: this.getCriteriaObject(this.queryParamsModel)
        }
        for (const param of event.criterions) {
          if (Array.isArray(param.value)) {
            param.value = param.value.join(',')
          }
        }
        return [event]
      } else {
        return []
      }
      // else {
      //   this.$message.warn('不能查询空条件')
      // }
    },
    isNullArray(array) {
      // 判断是不是空数组对象
      if (!array || array.length === 0) {
        return true
      }
      if (array.length === 1) {
        const obj = array[0]
        if (!obj.fieldName || (obj.value == null || obj.value === '') || !obj.operator) {
          return true
        }
      }
      return false
    },
    // 去掉数组中的空对象
    // removeEmptyObject(arr) {
    //   const array = JSON.parse(JSON.stringify(arr)) // utils.cloneObject(arr)
    //   const list = []
    //   for (let i = 0; i < array.length; i++) {
    //     const item = array[i]
    //     if (item == null || Object.keys(item).length <= 0) {
    //       array.splice(i--, 1)
    //     } else {
    //       if (Array.isArray(item.options)) {
    //         // 如果有字典属性，就不需要保存 options 了
    //         if (item.dictCode) {
    //           // 去掉特殊属性
    //           delete item.options
    //         }
    //       }
    //       list.push({
    //         value: item.value,
    //         operator: item.operator,
    //         fieldName: item.fieldName
    //       })
    //     }
    //   }
    //   return list
    // },
    getCriteriaObject(arr) {
      const list = []
      arr.forEach(item => {
        if (item != null && Object.keys(item).length > 0) {
          list.push({
            value: item.value,
            operator: item.operator,
            fieldName: item.fieldName
          })
        }
      })
      return list
    },
    /** 判断是否允许多选 */
    allowMultiple(item) {
      return item.operator === 'IN'
    },

    handleRuleChange(item, newValue) {
      const oldValue = item.operator
      this.$set(item, 'operator', newValue)
      // 上一个规则是否是 in，且type是字典或下拉
      if (oldValue === 'IN') {
        if (item.dictCode || item.options instanceof Array) {
          let value = item.value
          if (typeof item.value === 'string') {
            value = item.value.split(',')[0]
          } else if (Array.isArray(item.val)) {
            value = item.value[0]
          }
          this.$set(item, 'value', value)
        }
      }
    },
    getDictCode(item) {
      return item.dictTable ? item.dictTable + ',' + item.fieldName + ',' + item.dictCode : item.dictCode
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    resetLine() {
      this.queryParamsModel = []
      this.addNewLine()
    },
    getProps(fieldName) {
      return fieldName ? this.fieldObj[fieldName].props || {} : {}
    }
  },
  mounted() {
    this.isNewLine && this.addNewLine()
  }
}
</script>
<style scoped>
/* .container {
  position: relative;
}
.overlay {
  position: absolute;
  left: 0px;
  top: 0px;
  right: 0px;
  bottom: 0px;
} */
</style>
